package com.example.audiowebviewdemo;

import static com.google.common.truth.Truth.assertThat;

import android.webkit.WebView;

import androidx.test.core.app.ActivityScenario;
import androidx.test.ext.junit.runners.AndroidJUnit4;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 简单的 WebView 音频播放测试
 * 用于方便测试音频播放功能
 */
@RunWith(AndroidJUnit4.class)
public class MainActivityInstrumentedTest {

    private ActivityScenario<MainActivity> scenario;

    @Before
    public void launchActivity() {
        scenario = ActivityScenario.launch(MainActivity.class);
    }

    @After
    public void closeActivity() {
        if (scenario != null) {
            scenario.close();
        }
    }

    /**
     * 测试通过 JavaScript 调用音频播放函数
     * 使用方法：将你的音频流链接 URL 替换到下面的测试中
     */
    @Test
    public void webView_playAudio_viaJavaScript() throws InterruptedException {
        // TODO: 替换为你的实际音频流链接
        //249
         String testStreamUrl = "https://rr2---sn-qja5mc-5h.googlevideo.com/videoplayback?expire=1762602151&ei=R9gOae7nMtCRsfIP4cvS0Ak&ip=2605%3A52c0%3A1%3A713%3A6cff%3Ad8ff%3Afe33%3Ad616&id=o-ALPBZi5fzxNK9pLE2L170Csgdq9UDvZQtBiqoVj7AmSB&itag=249&source=youtube&requiressl=yes&xpc=EgVo2aDSNQ%3D%3D&met=1762580551%2C&mh=bd&mm=31%2C26&mn=sn-qja5mc-5h%2Csn-o097znz7&ms=au%2Conr&mv=m&mvi=2&pl=48&rms=au%2Cau&gcr=us&initcwndbps=2503750&bui=AdEuB5TQMcLhgXvtPBazwZxGqkfjLJGDYmgxrrfsHuY0e94OhYKoB0UK_Gkq1aGHSPyveT9t7Gixz_Qe&spc=6b0G_ERLiQKaKKT9aJZO9inM0I67sKzSI9Dq4kt0WUl8jgqiFRyRhA&vprv=1&svpuc=1&mime=audio%2Fwebm&ns=IVbJoE6jNuy5QB0chNRtHUsQ&rqh=1&gir=yes&clen=1316105&dur=161.081&lmt=1762478393708475&mt=1762580220&fvip=4&keepalive=yes&fexp=51552689%2C51565115%2C51565681%2C51580968&c=WEB_REMIX&sefc=1&txp=5532534&n=o9_3HLVfdRjLDA&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cxpc%2Cgcr%2Cbui%2Cspc%2Cvprv%2Csvpuc%2Cmime%2Cns%2Crqh%2Cgir%2Cclen%2Cdur%2Clmt&lsparams=met%2Cmh%2Cmm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Crms%2Cinitcwndbps&lsig=APaTxxMwRgIhAJW3ubDRUHkKaTnLQoSAEvXfq2RtA3aKAJ0vuTzsRDL-AiEAo5TGOKnnbuUbzgckVzujJ0bx2ZHWGnl8LrU1dpEjRZY%3D&sig=AJfQdSswRgIhAKeQ77q8LmfF6-Lzy_AKJCPKxGAK7goMa8lAuf0AKjMfAiEA5MusfEuXQZF_SdWTIy-scdvcsgvt7OIVjpqplK4V-TM%3D";
        //250
        testStreamUrl = "https://rr2---sn-qja5mc-5h.googlevideo.com/videoplayback?expire=1762602151&ei=R9gOae7nMtCRsfIP4cvS0Ak&ip=2605%3A52c0%3A1%3A713%3A6cff%3Ad8ff%3Afe33%3Ad616&id=o-ALPBZi5fzxNK9pLE2L170Csgdq9UDvZQtBiqoVj7AmSB&itag=250&source=youtube&requiressl=yes&xpc=EgVo2aDSNQ%3D%3D&met=1762580551%2C&mh=bd&mm=31%2C26&mn=sn-qja5mc-5h%2Csn-o097znz7&ms=au%2Conr&mv=m&mvi=2&pl=48&rms=au%2Cau&gcr=us&initcwndbps=2503750&bui=AdEuB5TQMcLhgXvtPBazwZxGqkfjLJGDYmgxrrfsHuY0e94OhYKoB0UK_Gkq1aGHSPyveT9t7Gixz_Qe&spc=6b0G_ERLiQKaKKT9aJZO9inM0I67sKzSI9Dq4kt0WUl8jgqiFRyRhA&vprv=1&svpuc=1&mime=audio%2Fwebm&ns=IVbJoE6jNuy5QB0chNRtHUsQ&rqh=1&gir=yes&clen=1724763&dur=161.081&lmt=1762478401546891&mt=1762580220&fvip=4&keepalive=yes&fexp=51552689%2C51565115%2C51565681%2C51580968&c=WEB_REMIX&sefc=1&txp=5532534&n=o9_3HLVfdRjLDA&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cxpc%2Cgcr%2Cbui%2Cspc%2Cvprv%2Csvpuc%2Cmime%2Cns%2Crqh%2Cgir%2Cclen%2Cdur%2Clmt&lsparams=met%2Cmh%2Cmm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Crms%2Cinitcwndbps&lsig=APaTxxMwRgIhAJW3ubDRUHkKaTnLQoSAEvXfq2RtA3aKAJ0vuTzsRDL-AiEAo5TGOKnnbuUbzgckVzujJ0bx2ZHWGnl8LrU1dpEjRZY%3D&sig=AJfQdSswRAIgS2PtrA__9LLoe2yAEXhu4F0ftcRP6IUa57Ge17gwlmcCIAT0fsRBvAjdzxG26mUvoy9X46194lkCplqv3sFNqKSL";

        //249
        testStreamUrl = "https://rr2---sn-qja5mc-5h.googlevideo.com/videoplayback?expire=1762602151&ei=R9gOae7nMtCRsfIP4cvS0Ak&ip=2605%3A52c0%3A1%3A713%3A6cff%3Ad8ff%3Afe33%3Ad616&id=o-ALPBZi5fzxNK9pLE2L170Csgdq9UDvZQtBiqoVj7AmSB&itag=249&source=youtube&requiressl=yes&xpc=EgVo2aDSNQ%3D%3D&met=1762580551%2C&mh=bd&mm=31%2C26&mn=sn-qja5mc-5h%2Csn-o097znz7&ms=au%2Conr&mv=m&mvi=2&pl=48&rms=au%2Cau&gcr=us&initcwndbps=2503750&bui=AdEuB5TQMcLhgXvtPBazwZxGqkfjLJGDYmgxrrfsHuY0e94OhYKoB0UK_Gkq1aGHSPyveT9t7Gixz_Qe&spc=6b0G_ERLiQKaKKT9aJZO9inM0I67sKzSI9Dq4kt0WUl8jgqiFRyRhA&vprv=1&svpuc=1&mime=audio%2Fwebm&ns=IVbJoE6jNuy5QB0chNRtHUsQ&rqh=1&gir=yes&clen=1316105&dur=161.081&lmt=1762478393708475&mt=1762580220&fvip=4&keepalive=yes&fexp=51552689%2C51565115%2C51565681%2C51580968&c=WEB_REMIX&sefc=1&txp=5532534&n=o9_3HLVfdRjLDA&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cxpc%2Cgcr%2Cbui%2Cspc%2Cvprv%2Csvpuc%2Cmime%2Cns%2Crqh%2Cgir%2Cclen%2Cdur%2Clmt&lsparams=met%2Cmh%2Cmm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Crms%2Cinitcwndbps&lsig=APaTxxMwRgIhAJW3ubDRUHkKaTnLQoSAEvXfq2RtA3aKAJ0vuTzsRDL-AiEAo5TGOKnnbuUbzgckVzujJ0bx2ZHWGnl8LrU1dpEjRZY%3D&sig=AJfQdSswRgIhAKeQ77q8LmfF6-Lzy_AKJCPKxGAK7goMa8lAuf0AKjMfAiEA5MusfEuXQZF_SdWTIy-scdvcsgvt7OIVjpqplK4V-TM%3D";

        //140
        testStreamUrl = "https://rr2---sn-qja5mc-5h.googlevideo.com/videoplayback?expire=1762602151&ei=R9gOae7nMtCRsfIP4cvS0Ak&ip=2605%3A52c0%3A1%3A713%3A6cff%3Ad8ff%3Afe33%3Ad616&id=o-ALPBZi5fzxNK9pLE2L170Csgdq9UDvZQtBiqoVj7AmSB&itag=140&source=youtube&requiressl=yes&xpc=EgVo2aDSNQ%3D%3D&met=1762580551%2C&mh=bd&mm=31%2C26&mn=sn-qja5mc-5h%2Csn-o097znz7&ms=au%2Conr&mv=m&mvi=2&pl=48&rms=au%2Cau&gcr=us&initcwndbps=2503750&bui=AdEuB5TQMcLhgXvtPBazwZxGqkfjLJGDYmgxrrfsHuY0e94OhYKoB0UK_Gkq1aGHSPyveT9t7Gixz_Qe&spc=6b0G_ERLiQKaKKT9aJZO9inM0I67sKzSI9Dq4kt0WUl8jgqiFRyRhA&vprv=1&svpuc=1&mime=audio%2Fmp4&ns=IVbJoE6jNuy5QB0chNRtHUsQ&rqh=1&gir=yes&clen=2608723&dur=161.064&lmt=1762478403864070&mt=1762580220&fvip=4&keepalive=yes&fexp=51552689%2C51565115%2C51565681%2C51580968&c=WEB_REMIX&sefc=1&txp=5532534&n=o9_3HLVfdRjLDA&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cxpc%2Cgcr%2Cbui%2Cspc%2Cvprv%2Csvpuc%2Cmime%2Cns%2Crqh%2Cgir%2Cclen%2Cdur%2Clmt&lsparams=met%2Cmh%2Cmm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Crms%2Cinitcwndbps&lsig=APaTxxMwRgIhAJW3ubDRUHkKaTnLQoSAEvXfq2RtA3aKAJ0vuTzsRDL-AiEAo5TGOKnnbuUbzgckVzujJ0bx2ZHWGnl8LrU1dpEjRZY%3D&sig=AJfQdSswRQIgJhlAd9D6n8Eo1GBuVKSSMeAp769F8JNer9cc9APZq4cCIQCiGU-PJHicDZzVZteQQpVZmC6Lohgo1ALM8u2Vx9mLog%3D%3D";

        //251
        testStreamUrl = "https://rr2---sn-qja5mc-5h.googlevideo.com/videoplayback?expire=1762602151&ei=R9gOae7nMtCRsfIP4cvS0Ak&ip=2605%3A52c0%3A1%3A713%3A6cff%3Ad8ff%3Afe33%3Ad616&id=o-ALPBZi5fzxNK9pLE2L170Csgdq9UDvZQtBiqoVj7AmSB&itag=251&source=youtube&requiressl=yes&xpc=EgVo2aDSNQ%3D%3D&met=1762580551%2C&mh=bd&mm=31%2C26&mn=sn-qja5mc-5h%2Csn-o097znz7&ms=au%2Conr&mv=m&mvi=2&pl=48&rms=au%2Cau&gcr=us&initcwndbps=2503750&bui=AdEuB5TQMcLhgXvtPBazwZxGqkfjLJGDYmgxrrfsHuY0e94OhYKoB0UK_Gkq1aGHSPyveT9t7Gixz_Qe&spc=6b0G_ERLiQKaKKT9aJZO9inM0I67sKzSI9Dq4kt0WUl8jgqiFRyRhA&vprv=1&svpuc=1&mime=audio%2Fwebm&ns=IVbJoE6jNuy5QB0chNRtHUsQ&rqh=1&gir=yes&clen=3345493&dur=161.081&lmt=1762478399795205&mt=1762580220&fvip=4&keepalive=yes&fexp=51552689%2C51565115%2C51565681%2C51580968&c=WEB_REMIX&sefc=1&txp=5532534&n=o9_3HLVfdRjLDA&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cxpc%2Cgcr%2Cbui%2Cspc%2Cvprv%2Csvpuc%2Cmime%2Cns%2Crqh%2Cgir%2Cclen%2Cdur%2Clmt&lsparams=met%2Cmh%2Cmm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Crms%2Cinitcwndbps&lsig=APaTxxMwRgIhAJW3ubDRUHkKaTnLQoSAEvXfq2RtA3aKAJ0vuTzsRDL-AiEAo5TGOKnnbuUbzgckVzujJ0bx2ZHWGnl8LrU1dpEjRZY%3D&sig=AJfQdSswRAIgFiwM0Whhg7EpDbJmllJnepLApF8k6aAHIJDDRpFp8ioCIDrpOJscWNtOfTetK_FKTXDx5ufBAzG5Mm2-G0mISI_s";

        //18
        testStreamUrl = "https://rr2---sn-qja5mc-5h.googlevideo.com/videoplayback?expire=1762602151&ei=R9gOae7nMtCRsfIP4cvS0Ak&ip=2605%3A52c0%3A1%3A713%3A6cff%3Ad8ff%3Afe33%3Ad616&id=o-ALPBZi5fzxNK9pLE2L170Csgdq9UDvZQtBiqoVj7AmSB&itag=18&source=youtube&requiressl=yes&xpc=EgVo2aDSNQ%3D%3D&met=1762580551%2C&mh=bd&mm=31%2C26&mn=sn-qja5mc-5h%2Csn-o097znz7&ms=au%2Conr&mv=m&mvi=2&pl=48&rms=au%2Cau&gcr=us&initcwndbps=2503750&bui=AdEuB5T7MtaXN6929Clx4AFKqNvySq5jRk6mIzJQlbiN0fEl4ET1KI4AvnOHhwSbT4oExQlcfHdfl_E5&spc=6b0G_ERIiQKaKKT9aJZO9inM0I67sKzSI9Dq4kt0WUl8jgqSEPSRHALJ&vprv=1&svpuc=1&mime=video%2Fmp4&ns=_J-KuXn6aVH_q6KmRednKzkQ&rqh=1&gir=yes&clen=2508413&ratebypass=yes&dur=161.123&lmt=1762478622960039&mt=1762580220&fvip=4&fexp=51552689%2C51565115%2C51565681%2C51580968&c=WEB_REMIX&sefc=1&txp=5538534&n=VkI4Pf9l01B9-w&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cxpc%2Cgcr%2Cbui%2Cspc%2Cvprv%2Csvpuc%2Cmime%2Cns%2Crqh%2Cgir%2Cclen%2Cratebypass%2Cdur%2Clmt&lsparams=met%2Cmh%2Cmm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Crms%2Cinitcwndbps&lsig=APaTxxMwRgIhAJW3ubDRUHkKaTnLQoSAEvXfq2RtA3aKAJ0vuTzsRDL-AiEAo5TGOKnnbuUbzgckVzujJ0bx2ZHWGnl8LrU1dpEjRZY%3D&sig=AJfQdSswRgIhAIh9i_Xldwa8RZ88-KlITziB0b16oZWPuGTvhc4vEpATAiEA9w0EUODkQpWiBEhr3CCX_oj_3uq_accbsqQ1foP8A4o%3D";

        final String finalTestStreamUrl = testStreamUrl;

        // 使用两个 latch：一个等待音频准备好，一个等待开始播放
        final CountDownLatch readyLatch = new CountDownLatch(1);
        final CountDownLatch playLatch = new CountDownLatch(1);
        
        scenario.onActivity(activity -> {
            try {
                // 通过反射获取 WebView
                java.lang.reflect.Field field = MainActivity.class.getDeclaredField("webView");
                field.setAccessible(true);
                WebView webView = (WebView) field.get(activity);
                
                if (webView != null) {
                    // 等待页面加载完成
                    webView.postDelayed(() -> {
                        android.util.Log.d("AudioTest", "开始调用 startAudio");
                        
                        // 调用 JavaScript 函数开始加载音频
                        String js = String.format("startAudio('%s');", finalTestStreamUrl.replace("'", "\\'"));
                        webView.evaluateJavascript(js, value -> {
                            android.util.Log.d("AudioTest", "startAudio JavaScript executed: " + value);
                        });
                        
                        // 等待音频准备好后自动播放
                        // 通过轮询检查音频状态
                        webView.postDelayed(() -> {
                            checkAudioReadyAndPlay(webView, readyLatch, playLatch);
                        }, 3000);
                    }, 2000);
                } else {
                    readyLatch.countDown();
                    playLatch.countDown();
                }
            } catch (Exception e) {
                android.util.Log.e("AudioTest", "Error: " + e.getMessage(), e);
                readyLatch.countDown();
                playLatch.countDown();
            }
        });
        
        // 等待音频准备好（最多 30 秒）
        android.util.Log.d("AudioTest", "等待音频准备好...");
        boolean ready = readyLatch.await(30, TimeUnit.SECONDS);
        assertThat(ready).isTrue();
        android.util.Log.d("AudioTest", "音频已准备好，等待开始播放...");
        
        // 等待开始播放（最多 10 秒）
        boolean playing = playLatch.await(10, TimeUnit.SECONDS);
        assertThat(playing).isTrue();
        android.util.Log.d("AudioTest", "音频已开始播放！");
        
        // 让音频播放一段时间（最多 5 分钟）
        android.util.Log.d("AudioTest", "音频开始播放，将播放最多 5 分钟...");
        Thread.sleep(5 * 60 * 1000); // 5 分钟 = 5 * 60 * 1000 毫秒
        android.util.Log.d("AudioTest", "测试完成，音频已播放 5 分钟");
    }
    
    private void checkAudioReadyAndPlay(WebView webView, CountDownLatch readyLatch, CountDownLatch playLatch) {
        // 检查音频是否准备好
        webView.evaluateJavascript(
            "(function() { " +
            "  if (typeof window.audioInstance !== 'undefined' && window.audioInstance) { " +
            "    return window.audioInstance.readyState >= 2 ? 'ready' : 'loading'; " +
            "  } " +
            "  return 'not_initialized'; " +
            "})();",
            readyState -> {
                android.util.Log.d("AudioTest", "Audio readyState: " + readyState);
                
                if (readyState != null && readyState.contains("ready")) {
                    if (readyLatch.getCount() > 0) {
                        readyLatch.countDown();
                        android.util.Log.d("AudioTest", "音频已准备好，开始播放...");
                        
                        // 调用 playAudio
                        webView.evaluateJavascript("playAudio();", value -> {
                            android.util.Log.d("AudioTest", "playAudio called: " + value);
                            
                            // 等待一下，然后检查是否正在播放
                            webView.postDelayed(() -> {
                                checkAudioPlaying(webView, playLatch);
                            }, 2000);
                        });
                    }
                } else {
                    // 如果还没准备好，继续检查
                    webView.postDelayed(() -> {
                        checkAudioReadyAndPlay(webView, readyLatch, playLatch);
                    }, 1000);
                }
            }
        );
    }
    
    private void checkAudioPlaying(WebView webView, CountDownLatch playLatch) {
        // 检查音频是否正在播放
        webView.evaluateJavascript(
            "(function() { " +
            "  if (typeof window.audioInstance !== 'undefined' && window.audioInstance) { " +
            "    return !window.audioInstance.paused ? 'playing' : 'paused'; " +
            "  } " +
            "  return 'not_initialized'; " +
            "})();",
            playingState -> {
                android.util.Log.d("AudioTest", "Audio playing state: " + playingState);
                
                if (playingState != null && playingState.contains("playing")) {
                    if (playLatch.getCount() > 0) {
                        playLatch.countDown();
                        android.util.Log.d("AudioTest", "音频正在播放！");
                    }
                } else {
                    // 如果还没开始播放，继续检查
                    webView.postDelayed(() -> {
                        checkAudioPlaying(webView, playLatch);
                    }, 1000);
                }
            }
        );
    }

    /**
     * 测试音频控制函数（播放、暂停、停止）
     */
    @Test
    public void webView_audioControl_viaJavaScript() throws InterruptedException {
        final CountDownLatch latch = new CountDownLatch(1);
        
        scenario.onActivity(activity -> {
            try {
                java.lang.reflect.Field field = MainActivity.class.getDeclaredField("webView");
                field.setAccessible(true);
                WebView webView = (WebView) field.get(activity);
                
                if (webView != null) {
                    webView.postDelayed(() -> {
                        // 测试播放控制函数
                        webView.evaluateJavascript("playAudio();", null);
                        webView.postDelayed(() -> {
                            webView.evaluateJavascript("pauseAudio();", null);
                            webView.postDelayed(() -> {
                                webView.evaluateJavascript("stopAudio();", value -> {
                                    android.util.Log.d("AudioTest", "Control functions executed");
                                    latch.countDown();
                                });
                            }, 500);
                        }, 500);
                    }, 2000);
                } else {
                    latch.countDown();
                }
            } catch (Exception e) {
                android.util.Log.e("AudioTest", "Error: " + e.getMessage());
                latch.countDown();
            }
        });
        
        assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue();
    }
}

